/*
 * @Date: 2022-12-29 15:15:49
 * @LastEditors: 旧轩00°°
 * @LastEditTime: 2022-12-30 15:25:13
 * @FilePath: /vue3-ts-vite-pinia-husky/src/utils/handleRoutes.ts
 */
import type { RouteRecordRaw } from 'vue-router'

/**
 * 给每个路由设置默认的跳转连接
 * @param {Array} routes 路由列表
 * @param {String} prefix 路由前缀
 */
export function setDefaultRoute(
  routes: RouteRecordRaw[],
  prefix: string = '/main'
) {
  routes.forEach((item) => {
    if (item.children && item.children.length > 0) {
      item.redirect = item.children[0].path

      setDefaultRoute(item.children)
    }

    if (item.path) {
      item.path = prefix + item.path
    }
  })
  return routes
}

/**
 * 接口返回的接口是树状结构的 可采用此递归方法过滤路由
 * @param {Array}  userRoutes 接口返回的路由列表(动态路由)
 * @param {Array}  allRoutes   所有路由的列表
 * @return {Array} resRoutes   过滤之后符合条件的路由
 */
export const filterRecursionRoutes = (
  userRoutes: any,
  allRoutes: RouteRecordRaw[]
) => {
  let resRoutes = []
  userRoutes.forEach((item) => {
    allRoutes.forEach((item2) => {
      if (item.name === item2.name) {
        if (item2.children && item2.children.length > 0) {
          item.children = filterRecursionRoutes(item.children, item2.children)
        }
        // 组件赋值
        item2.component && (item.component = item2.component)
        resRoutes.push(item)
      }
    })
  })
  return resRoutes
}

// 根据路由匹配面包屑
interface IBreadcrumbs {
  name: string
  path: string
}
export function mapPathToBreadcrumbs(path: string, userRoutes: any[]) {
  let breadcrumbs: IBreadcrumbs[] = []
  userRoutes.forEach((item) => {
    item.children.forEach((item2) => {
      if (path === item2.path) {
        // 记录父级的菜单
        breadcrumbs.push({ name: item.name, path: item.path })
        // 记录当前的菜单
        breadcrumbs.push({ name: item2.name, path: item2.path })
      }
    })
  })
  return breadcrumbs
}
